package com.ncwu.interfaces.facade;

import com.ncwu.application.service.UserService;
import com.ncwu.domain.entity.User;
import com.ncwu.infrastructure.exception.CmdcException;
import com.ncwu.infrastructure.exception.ErrorEnum;
import com.ncwu.infrastructure.util.ObjectUtils;
import com.ncwu.interfaces.dto.Result;
import com.ncwu.interfaces.dto.request.CodeLoginDTO;
import com.ncwu.interfaces.dto.request.PassWordLoginDTO;
import com.ncwu.interfaces.dto.request.PwdAndCaptchaDTO;
import com.ncwu.interfaces.dto.request.RegisterDTO;
import com.ncwu.interfaces.dto.response.UserDTO;
import com.ncwu.interfaces.dto.response.UserDetailsDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;

/**
 * @author : wuwensheng
 * @date : 10:24 2020/7/1
 */
@RestController
@Slf4j
@Api(tags = "用户管理")
public class UserFacade {
    @Autowired
    private UserService userService;

    @ApiOperation("获取用户权限")
    @RequiresRoles(value = {"admin", "common"}, logical = Logical.OR)
    @RequiresPermissions(value = {"resetPassword", "queryMyUserInfo"}, logical = Logical.OR)
    @GetMapping(value = "/v1.0/shiro/getUserPermission")
    public Result getUserPermission() {
        log.info("访问接口getUserPermission成功");
        return new Result();
    }

    @ApiOperation("获取用户")
    @RequiresRoles(value = {"admin"})
    @GetMapping(value = "/v1.0/shiro/getUser")
    public Result getUser() {
        log.info("访问getUser接口成功");
        List<User> userList = userService.getUser();
        return new Result<>(ObjectUtils.convert(userList,UserDTO.class));
    }

    @ApiOperation("用户密码登录")
    @PostMapping(value = "/user/passwordLogin", name = "用户密码登录")
    public Result passwordLogin(@RequestBody @Valid PassWordLoginDTO passWordLoginDTO) {
        log.info("传递的请求参数:{}", passWordLoginDTO);
        Result result;
        try {
            result = new Result<>(userService.passWordLogin(passWordLoginDTO.getUserId(), passWordLoginDTO.getPassword()));
        } catch (CmdcException e) {
            throw e;
        }
        return result;
    }

    @ApiOperation("用户注册")
    @PostMapping(value = "/user/register", name = "用户注册")
    public Result userRegister(@RequestBody @Valid RegisterDTO registerDTO) {
        Result result;
        try {
            userService.register(registerDTO.getUserId(), registerDTO.getUserName(), registerDTO.getPassword(), registerDTO.getRemark());
            result = new Result();
        } catch (CmdcException e) {
            throw e;
        }
        return result;
    }

    @ApiOperation("用户发送登录验证码")
    @GetMapping(value = "/user/sendVerificationCode")
    public Result sendVerificationCode(String userId) {
        if (StringUtils.isEmpty(userId)) {
            throw new CmdcException(ErrorEnum.BAD_PARAM);
        }
        try {
            Integer verificationCode = userService.sendVerificationCode(userId);
            return new Result<>(verificationCode);
        } catch (CmdcException e) { //如果是我们的异常 直接扔出去
            throw e;
        }
    }

    @ApiOperation("用户验证码登录")
    @PostMapping(value = "/user/verificationCodeLogin", name = "用户验证码登录")
    public Result verificationCodeLogin(@RequestBody @Valid CodeLoginDTO codeLoginDTO) {
        Result result;
        try {
            result = new Result<>(userService.verificationCodeLogin(codeLoginDTO.getUserId(), codeLoginDTO.getCode()));
        } catch (CmdcException e) {
            throw e;
        }
        return result;
    }

    @ApiOperation("获取图片验证码接口")
    @GetMapping(value = "/user/captcha", name = "获取图片验证码接口")
    @ApiImplicitParam(name = "userId", value = "手机号", required = true, dataTypeClass = String.class)
    public void captCha(HttpServletResponse response, String userId){
        try{
            response.setHeader("Cache-Control", "no-store, no-cache");
            response.setContentType("image/jpeg");
            //获取图片验证码
            BufferedImage image = userService.getCaptcha(userId);
            ServletOutputStream out = response.getOutputStream();
            ImageIO.write(image, "jpg", out);
            IOUtils.closeQuietly(out);
        } catch (IOException o){
            throw new CmdcException(ErrorEnum.GET_CAPTCHA_ERROR);
        }
    }

    @ApiOperation("用户账号、密码、验证码登录")
    @PostMapping(value = "/user/pwdAndCaptchaLogin", name = "用户验证码登录")
    public Result<UserDetailsDTO> pwdAndCaptchaLogin(@RequestBody @Valid PwdAndCaptchaDTO pwdAndCaptchaDTO) {
        try {
            return new Result<>(userService.pwdAndCaptchaLogin(pwdAndCaptchaDTO.getUserId(), pwdAndCaptchaDTO.getPassword(), pwdAndCaptchaDTO.getCode()));
        } catch (CmdcException e) {
            throw e;
        }
    }

}
